package com.blm.handler;

import com.blm.common.Message;
import com.blm.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {

    // todo: 可能覆盖
    private static Map<Long, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        log.info("user {} connected", userId);

        sessions.put(userId, session);
        session.sendMessage(new TextMessage("Welcome to the chat!"));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        log.info("user {} disconnected", userId);
        sessions.remove(userId);
    }

    private static void sendMessageToUser(Long userId, Object message) {
        WebSocketSession session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                String jsonMessage = JsonUtil.toJson(message);
                session.sendMessage(new TextMessage(jsonMessage));
                log.debug("Message sent to user {}: {}", userId, jsonMessage);
            } catch (Exception e) {
                log.error("Error sending message to user {}: {}", userId, e.getMessage());
            }
        } else {
            log.warn("User {} is not connected", userId);
        }
    }

    public static void notify(Long userId, Message.MessageType messageType, Object content) {
        Message msg = new Message(messageType, content);
        sendMessageToUser(userId, msg);
        log.info("Notification sent to user {}: {}", userId, msg);
    }
}
